using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace PP.Basic.Pool
{
    /// <summary>
    /// ObjectPools对象
    /// </summary>
    public class ObjectPools
    {
        private const string Tag = nameof(ObjectPools);

        // Private Variables Begin
        private string _id;
        private readonly Dictionary<Type, object> _pools = new Dictionary<Type, object>();
        // Private Variables End

        // Static Variables Begin
        private static Dictionary<string, ObjectPools> _instances;
        private static Dictionary<string, ObjectPools> Instances => _instances ?? (_instances = new Dictionary<string, ObjectPools>());
        // Static Variables End

        // Static Methods Begin
        public static ObjectPools GetInstance(string id = "")
        {
            ObjectPools pools;
            if (!Instances.TryGetValue(id, out pools))
            {
                pools = new ObjectPools(id);
                Instances.Add(id, pools);
            }
            return pools;
        }
        // Static Methods End

        // Ctor
        public ObjectPools(string id = "")
        {
            _id = id ?? "";
        }

        // Public Methods Begin
        public ObjectPool<T> GetPool<T>(Func<T> createFunc = null, Action<T> actionOnGet = null, Action<T> actionOnRelease = null,
            Action<T> actionOnDestroy = null, bool collectionCheck = true, int defaultCapacity = 10, int maxSize = 10000) where T : class, new()
        {
            var type = typeof(T);
            if (!_pools.TryGetValue(type, out var pool))
            {
                if ( createFunc == null)
                    createFunc = () => new T();

                pool = new ObjectPool<T>(createFunc, actionOnGet, actionOnRelease, actionOnDestroy, collectionCheck, defaultCapacity, maxSize);
                _pools[type] = pool;
            }
            return (ObjectPool<T>)pool;
        }
        // Public Methods End
    }
}
